<?php
require_once dirname(__FILE__) . '/metadata.php';
require_once dirname(__FILE__) . '/config.php';
require_once dirname(__FILE__) . '/EmailFetcher.class.php';
require_once dirname(__FILE__) . '/DbUtils.class.php';
require_once dirname(__FILE__) . '/includes/MiscUtils.class.php';
require_once dirname(__FILE__) . '/server.class.php';

$emails = array();
$mailHeader = array();
$mailAttach = array();
$mailBody = '';
$mail = new EmailFetcher();
$server_path = SERVER_ROOT . PATH . 'attaches/';

try {
  $connect = $mail->mailConnect('imap.gmail.com', 993, ENQ_GMAIL_USER,  ENQ_GMAIL_PASS, 'INBOX', 'ssl');
} catch (Exception $e) {
  MiscUtils::dump('Error1: ');
  MiscUtils::dump($e);
}

try {
  if ($connect) {
    for ($mailId = 0, $totalCount = $mail->mailTotalCount(); $mailId < $totalCount; $mailId++) {
      try {
        $mailHeader = $mail->mailHeader($mailId + 1);
      } catch (Exception $e) {
        MiscUtils::dump('Error3: ');
        MiscUtils::dump($e);
      }
      
      try {
        $mailBody = $mail->getBody($mailId + 1);
      } catch (Exception $e) {
        MiscUtils::dump('Error4: ');
        MiscUtils::dump($e);
      }
      
      try {
        $mailAttach = $mail->getAttach($mailId + 1, $server_path);
      } catch (Exception $e) {
        MiscUtils::dump('Error5: ');
        MiscUtils::dump($e);
      }
      
      
      $myPdo = DbUtils::createPdoInst();
      
      try {
        $min_id = 0;
        $opts = new stdClass();
        $opts->select_expr = 'MIN(t.enquiry_id) AS min_id';
        $tmps = DbUtils::get($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_emails', NULL, NULL, NULL, NULL, NULL, $opts)->d;
        if (count($tmps) > 0) {
          $min_id = $tmps[0]->min_id;
          $min_id = min(0, $min_id);
          --$min_id;
        }
      } catch (PDOException $e) {
        MiscUtils::dump('Error6: ');
        MiscUtils::dump($e);
      }
      
      if (isset($mailHeader['from'])) {
        if (strtolower($mailHeader['from']) == strtolower(DREAMLIFE_CN_ENQUIRY_MAIL)) {
          $tmps = explode("#", strip_tags($mailBody));
          $idx = 0; $index = 0;
          for ($i=0; $i<count($tmps); $i++) {
            $tmp = $tmps[$i];
            if (is_int(stripos($tmp, "Email Address:"))) {
              $idx = $i;
            }
            if (is_int(stripos($tmp, "Name:"))) {
              $index = $i;
            }
          }
          $mailHeader['from'] = $tmps[$idx+1];
          $mailHeader['fromName'] = $tmps[$index+1];
        }
      }
      
      $cus_mail = '';
      $normal_email = '';
      if (isset($mailHeader['from'])) {
      	$normal_email = $mailHeader['from'];
        if (strtolower($mailHeader['from']) == strtolower(ERROR_SEND_MAIL)) {
          if (is_int(stripos(strip_tags($mailBody), ERROR_SEND_MAIL_CONTENT_FIRST))) {
            $cus_mail = trim(substr(strip_tags($mailBody), strlen(ERROR_SEND_MAIL_CONTENT_FIRST), stripos(strip_tags($mailBody), ERROR_SEND_MAIL_CONTENT_SECOND) - strlen(ERROR_SEND_MAIL_CONTENT_FIRST)));
          }
          $cond_vals = new stdClass();
          $cond_vals->c = 't.email = :v1';
          $cond_vals->v = array(':v1' => $cus_mail);
          $tmp = DbUtils::get($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_emails', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
          if (count($tmp) > 0) {
            $mailHeader['from'] = $cus_mail;
          }
        }
      }
      
      try {
        if (!isset($emails[strtolower($mailHeader['from'])])) {
          $cond_vals = new stdClass();
          $cond_vals->c = 't.email = :v1';
          $cond_vals->v = array(':v1' => $mailHeader['from']);
          $tmp = DbUtils::get($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_emails', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
          if (count($tmp) == 0) {
            try {
              $email = new stdClass();
              $email->track_id = MiscUtils::unique();
              $email->enquiry_id = $min_id;
              $email->email = $mailHeader['from'];
              $email->name = $mailHeader['fromName'];
              $email->date1 = date('Y-m-d H:i:s', strtotime($mailHeader['date']));
              $email->date2 = '0000-00-00 00:00:00';
              $email->unread = 1;
              $email->replied_status = 0;
              $email->is_read = 0;
              DbUtils::add($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_emails', $email);
            } catch (PDOException $e) {
              MiscUtils::dump('Error7: ');
              MiscUtils::dump($e);
            }
            
            $emails[strtolower($mailHeader['from'])] = array($myPdo->lastInsertId(), 0, strtotime($mailHeader['date']));
          } else {
            $emails[strtolower($tmp[0]->email)] = array($tmp[0]->id, $tmp[0]->enquiry_id, max(strtotime($mailHeader['date']), strtotime($tmp[0]->date1)));
          }
        } else {
          $emails[strtolower($mailHeader['from'])][2] = max(strtotime($mailHeader['date']), $emails[$mailHeader['from']][2]);
        }
      } catch (PDOException $e) {
        MiscUtils::dump('Error8: ');
        MiscUtils::dump($e);
      }
        
      try {
        $structure = imap_fetchstructure($connect, $mailId + 1);
        $message = MiscUtils::pluginObj();
        $message->date1 = date('Y-m-d H:i:s', strtotime($mailHeader['date']));
        $message->date2 = '0000-00-00 00:00:00';
        $message->date3 = '0000-00-00 00:00:00';
        $message->attr1 = $emails[strtolower($mailHeader['from'])][0];
        $message->attr2 = $emails[strtolower($mailHeader['from'])][1];
        $message->attr3 = $mailHeader['subject'];
        $message->attr4 = $mailBody;
        $message->attr5 = 0;
        $message->attr6 = $structure->type;
        $message->attr7 = 0;
        $message->attr8 = $mailHeader['fromName'];
        $message->attr9 = $mailHeader['from'];
        $message->message_type = 0;
        $message->parent_id = 0;
        $message->reminding_type = 1;
        $message->reminding_days = 0;
        $message->reminding_date = '0000-00-00 00:00:00';
        $message->reminding_note = '';
        $message->is_closed = 0;
        $message->appointment_date = '0000-00-00 00:00:00';
        $message->appt_user_id = 0;
        $message->appt_user_name = '';
        $message->appointment_note = '';
        $message->is_visited = 0;
        $message->visited_date = '0000-00-00 00:00:00';
        $message->is_draft = 0;
        $message->is_new = 0;
        $message->is_sent = 0;
        $message->is_read = 0;
        $message->is_reminding_closed = 0;
        $message->ask_other = '';
        DbUtils::add($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_email_messages', $message);
        $message->id = $myPdo->lastInsertId();
      } catch (PDOException $e) {
      	MiscUtils::dump('Error9: ');
        MiscUtils::dump($e);
      }
      
      try {
        foreach ($mailAttach as $tmp) {
          $attach = new stdClass();
          $attach->track_id = MiscUtils::unique();
          $attach->enquiry_id = $emails[strtolower($mailHeader['from'])][1];
          $attach->email_id = $emails[strtolower($mailHeader['from'])][0];
          $attach->message_id = $message->id;
          $attach->name_on_server = $tmp[0];
          $attach->name = $tmp[1];
          $attach->size = (filesize($server_path . $tmp[0])) ? filesize($server_path . $tmp[0]) / 1000 : 0;
          DbUtils::add($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_email_message_attachments', $attach);
        }
      } catch (PDOException $e) {
        MiscUtils::dump('Error10: ');
        MiscUtils::dump($e);
      }
      
      try {
        $mail->mailDelete($mailId + 1);
      } catch (Exception $e) {
        MiscUtils::dump('Error11: ');
        MiscUtils::dump($e);
      }
      
    }
  
    try {
      foreach ($emails as &$email) {
        $cond_vals = new stdClass();
        $cond_vals->c = 't.attr1 = :v1 AND t.parent_id = :v2';
        $cond_vals->v = array(':v1' => $email[0], ':v2' => 0);
        $opts = new stdClass();
        $opts->select_expr = 'COUNT(t.id) AS count';
        $tmp = DbUtils::get($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_email_messages', $cond_vals, NULL, NULL, NULL, NULL, $opts)->d;
        
        $obj = new stdClass();
        $obj->id = $email[0];
        $obj->date1 = date('Y-m-d H:i:s', $email[2]);
        $obj->unread = $tmp[0]->count;
        $obj->replied_status = 0;
        $obj->is_read = 0;
        DbUtils::update($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_emails', $obj);
        
        if ($email[1] != 0) {
          $obj = new stdClass();
          $obj->id = $email[1];
          $obj->date1 = date('Y-m-d H:i:s', $email[2]);
          $obj->date_last_follow = date('Y-m-d H:i:s', $email[2]);
          DbUtils::update($myPdo, TABLE_NAME_PREFIX_MODULE . 'data_enquiry', $obj);
          
          $enqs = Server::get_enquiries($email[1]);
          Server::replied_status($enqs);
          Server::unread($enqs);
          Server::date1($enqs);
          Server::is_read($enqs);
          //转发booked掉的enquiry中这封邮件的信息
          if (BRANCH == 'syd') {
	          require_once dirname(__FILE__) . '/EmailForward.class.php';
	          EmailForward::forward_booked($email);
          }
        }
      }
    } catch (PDOException $e) {
      MiscUtils::dump('Error12: ');
      MiscUtils::dump($e);
    }
    
    try {
      $mail->closeMail();
    } catch (PDOException $e) {
      MiscUtils::dump('Error13: ');
      MiscUtils::dump($e);
    }
  }
} catch (Exception $e) {
  MiscUtils::dump('Error2: ');
  MiscUtils::dump($e);
}

?>
